<template>
  <el-form
    :model="addEditForm"
    ref="addEditForm"
    label-width="95px"
    label-position="left"
    class="pg-shaohuo-person-add-edit-franchisee-children">
    <el-dialog
      :title="`${type}加盟商`"
      :before-close="beforeDialogClose"
      :visible.sync="dialogVisible"
      width="50%">
      <!-- 表单主题
      -------------------------- -->
      <el-form-item 
        label="姓名"
        prop="realname"
        :rules="{ required: true, message: '请输入姓名', trigger: 'blur' }">
        <el-input v-model="addEditForm.realname"></el-input>
      </el-form-item>
      
      <el-form-item 
        label="手机号"
        prop="phone"
        :rules="[
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatorPhone, trigger: 'blur' }
        ]">
        <el-input v-model="addEditForm.phone"></el-input>
      </el-form-item>
      
      <el-form-item 
        :label="isEditing ? '新密码' : '密码'"
        prop="passwd"
        :rules="isEditing ? [
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ] : [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]">
        <el-input v-model="addEditForm.passwd"
          type="password"
          :placeholder="isEditing ? '需要修改密码请输入' : ''"></el-input>
      </el-form-item>
      
      <el-form-item 
        v-if="!isEditing || addEditForm.passwd"
        label="确认密码"
        prop="checkPasswd"
        :rules="[
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validatorCheckPasswd, trigger: 'blur' }
        ]">
        <el-input type="password"
          v-model="addEditForm.checkPasswd"></el-input>
      </el-form-item>
      
      <el-form-item 
        label="状态"
        prop="status">
        <el-switch
          v-model="addEditForm.status"
          active-text="正常"
          inactive-text="禁用"></el-switch>
      </el-form-item>

      <el-form-item 
        label="管理区域"
        prop="regions"
        :rules="{ required: true, message: '请选择管理区域', trigger: 'blur' }">
        <el-select
          v-model="addEditForm.regions"
          @visible-change="visibleChange"
          multiple
          :loading="!hasAllAreaList"
          placeholder="请选择管理区域">
          <el-option
            v-for="item in areaList"
            :key="item.region_id"
            :label="item.name"
            :value="item.region_id">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 底部按钮区
      -------------------------- -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary"
          @click="submitForm"
          :loading="loadingBtn === '确定'">确 定</el-button>
      </span>
    </el-dialog>
  </el-form>
</template>

<script>
import { ShaohuoFranchiseeService, ShaohuoPriceService } from 'services/Api'
import {
  btnLoadingMixin,
  formAddEditMixin,
  dialogCoreMixin
} from 'services/Public'
import { RegExService } from 'services/Util'
import { mapState } from 'vuex'

export default {
  mixins: [
    btnLoadingMixin,
    formAddEditMixin,
    dialogCoreMixin
  ],
  data () {
    return {
      addEditForm: {
        realname: '',
        phone: '',
        passwd: '',
        checkPasswd: '',
        status: true,
        regions: [] // 类型名字
      },
      areaList: null, // 区域列表
      hasAllAreaList: false // 是否已获取所有区域列表
    }
  },
  props: {
    metaData: {
      type: Object,
      default: () => { return {} }
    }
  },
  computed: {
    ...mapState([ 'acc_id' ]),
    franchiserId () {
      return this.$route.params.id
    },
    // 获取区列表参数
    getAreaByIdParam () {
      return {
        acc_id: this.acc_id,
        id: this.metaData.id || ''
      }
    },
    // 添加参数
    addFranchiserChildrenParam () {
      return {
        acc_id: this.acc_id,
        pid: this.franchiserId,
        realname: this.addEditForm.realname,
        phone: this.addEditForm.phone,
        passwd: this.addEditForm.passwd,
        region_ids: this.addEditForm.regions.join(','),
        status: this.addEditForm.status ? '0' : '1'
      }
    },
    // 修改参数
    alterFranchiserChildrenParam () {
      return {
        acc_id: this.acc_id,
        pid: this.franchiserId,
        uid: this.editData.uid,
        realname: this.addEditForm.realname,
        phone: this.addEditForm.phone,
        passwd: this.addEditForm.passwd,
        region_ids: this.addEditForm.regions.join(','),
        status: this.addEditForm.status ? '0' : '1'
      }
    }
  },
  methods: {
    // 下拉框出现/隐藏时触发
    visibleChange (boo) {
      // 出现时判断areaList是否已获取，没有则调用接口获取
      if (boo && !this.hasAllAreaList) this.getAreaByIdApi()
    },
    // 手机号验证
    validatorPhone (rule, value, cb) {
      if (RegExService.phone(value)) {
        cb()
      } else {
        cb(new Error('请输入合法的手机号'))
      }
    },
    // 确认密码验证
    validatorCheckPasswd (rule, value, cb) {
      if (value === this.addEditForm.passwd) {
        cb()
      } else {
        cb(new Error('两次输入密码不一致'))
      }
    },
    // 关闭弹窗前重置表单
    beforeDialogClose (done) {
      if (done) done()
      this.isEditing = false
      this.resetForm()
      this.areaList = [] // 可能有几个不同的区，每次关闭重置区数据
      this.hasAllAreaList = false
      this.resetByToogle = !this.resetByToogle
      this.addEditForm = {
        realname: '',
        phone: '',
        passwd: '',
        checkPasswd: '',
        status: true,
        regions: []
      }
    },
    // formAddEditMixin需要 - 编辑时将传入的源数据写入当前表单
    editDataHandler (v) {
      this.addEditForm.realname = v.realname || ''
      this.addEditForm.phone = v.phone || ''
      this.addEditForm.status = v.status === '正常'
      this.addEditForm.regions = v.region_info.map(i => i.region_id)
      if (!this.hasAllAreaList) {
        this.areaList = v.region_info.map(i => { return { region_id: i.region_id, name: i.name } })
      }
    },
    // formAddEditMixin需要 - 提交成功后的操作
    afterSubmitSuccess () {
      this.dialogComplete()
    },
    // 添加接口
    currentAddApi () {
      return ShaohuoFranchiseeService.addSonFranchiser(this.addFranchiserChildrenParam)
    },
    // 编辑接口
    currentEditApi () {
      return ShaohuoFranchiseeService.addSonFranchiser(this.alterFranchiserChildrenParam)
    },
    // 获取区列表接口
    async getAreaByIdApi () {
      const [ err, res ] = await ShaohuoPriceService.getCityAreaById(this.getAreaByIdParam)
      if (err) return this.$message.error(err.message || '获取失败')
      res.shift()
      this.areaList = res
      this.hasAllAreaList = true
    }
  }
}
</script>

<style lang="scss">
@import "src/styles/config/views.scss";

@include b(shaohuo-person-add-edit-franchisee-children) {
  .el-form-item__content > .el-input,
  .el-form-item__content > .el-select {
    width: 80%;
  }
  @include e(delete) {
    padding-left: $--padding-base;
  }
  
  .el-switch__label {
    font-weight: normal;
    color: $--color-text-regular;
    &.is-active {
      color: $--color-primary;
    }
  }
}
</style>
